import {createBrowserRouter, useMatches, useNavigate} from "react-router-dom";
import loadable from "@loadable/component";
import {DEFAULT_PATH, HOME_PAGE, LOGIN_PAGE} from "@utils/constants.js";

const modules = import.meta.glob('../pages/**/*.jsx')
export const AuthNode = ({path}) => {
    path = `../pages${path}.jsx`;
    const Component = memo(loadable(modules[path]));
    useEffect(() => {
        //充当路由守卫程序
        console.log('\x1b[94m%s\x1b[0m', "当前路由: " + location.pathname)
        if (location.pathname === LOGIN_PAGE) {
            console.log('\x1b[94m%s\x1b[0m', "进入登录页")
            if (localStorage.getItem('token')) {
                console.log('\x1b[94m%s\x1b[0m', "已有凭证,直接进入首页")
                location.href = HOME_PAGE
            }
        } else if (!localStorage.getItem('token')) {
            console.log('\x1b[94m%s\x1b[0m', "没有token,跳转到登录页")
            location.href = LOGIN_PAGE
        }
    }, [])
    return <Component/>
}
const NotFound = () => {
    const navigate = useNavigate();
    const matches = useMatches();
    useEffect(() => {
        //判断menus是否存在
        let menus = sessionStorage.getItem('menus');
        if (!menus) {
            navigate(HOME_PAGE, {replace: true})
        } else {
            menus = JSON.parse(menus)
            let first = addInterfaceDataRouter(menus)
            if (matches[0].id !== '404') navigate(location.pathname, {replace: true})
            else navigate(first.path, {replace: true})
        }
    }, [])
    return <></>
}
const ErrorPage = () => <>页面错误</>
const router = createBrowserRouter([
    {
        id: '/',
        path: '/',
        element: <AuthNode path={HOME_PAGE + DEFAULT_PATH}/>,
        errorElement: <ErrorPage/>
    },
    {
        id: '404',
        path: '*',
        element: <NotFound/>,
        errorElement: <ErrorPage/>
    }
])
/**
 * 动态扫描本地文件,添加路由
 * todo 未完成,目前都是根路由,未区分子路由,待处理,如果是一些简单项目,没有嵌套路由的可以直接使用
 */
const addLocalFileRouter = async (include) => {
    await Promise.all(
        Object.keys(modules).map(path => (async () => {
            let url;
            let fullPath = url = path.replace('../pages', '').replace('.jsx', '')
            if (fullPath.endsWith(DEFAULT_PATH)) {
                url = fullPath.replace(DEFAULT_PATH, '')
                if (include && !include.includes(url)) return;
            }else return
            console.log('\x1b[91m%s\x1b[0m', `动态添加路由成功,访问路径:${url},配置加载路径:${fullPath},源码完整路径:${path}`)
            router.routes.push({
                id: url,
                path: url,
                element: <AuthNode path={fullPath}/>,
                errorElement: <ErrorPage/>
            })
        })())
    )
    console.log('\x1b[91m%s\x1b[0m', "动态添加路由完成")
}
/**
 * 当前项目只加载登录页和首页
 */
addLocalFileRouter([LOGIN_PAGE, HOME_PAGE])
/**
 * 接口调用，动态添加权限路由
 */
export const addInterfaceDataRouter = (arr, _) => {
    if (!arr || !arr.length) return;
    let flag = false;
    if (!_) {
        _ = router.routes.find(e => e.id === HOME_PAGE)
        flag = true;
    }
    _.children = arr.map((e, i) => {
        let item = {
            id: e.id,
            path: e.path,
            element: <AuthNode path={e.component}/>,
            errorElement: <ErrorPage/>
        }
        sessionStorage.setItem(e.path, JSON.stringify(e))
        addInterfaceDataRouter(e.children, item)
        return item
    })
    if (!flag) return
    let first = _.children[0]
    while (_.children[0].children && _.children[0].children.length > 0) {
        first = _.children[0].children[0]
    }
    return first;
}

export default router;